package com.lh.controller;

import com.lh.entity.Result;
import com.lh.entity.User;
import com.lh.service.UserService;
import com.lh.utils.JwtUtil;
import com.lh.utils.Md5Util;
import com.lh.utils.ThreadLocalUtil;
import jakarta.validation.constraints.Pattern;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
/**
我是A，这是我今天的工作
 */

@RestController
@RequestMapping("/user")
@Validated
public class UserController {

    @Autowired
    private UserService userService;
//    --注入redis操作对象
    @Autowired
    private StringRedisTemplate stringRedisTemplate;



    @PostMapping("/register")
    public Result register (@Pattern(regexp = "^\\S{5,16}$") String username,@Pattern(regexp = "^\\S{5,16}$") String password) {
      User user=  userService.findUserByName(username);
      if (user==null) {
//          可以注册
       Result r=   userService.register(username,password);
       return r;
      }else{
//          不能注册
          return new Result(0,"用户已存在",null);
      }

    }


//    登录
    @PostMapping("/login")
    public Result<String> login(String username, String password) {
        //判断该用户是否存在
        User user = userService.findUserByName(username);
        if (user==null) {
            //用户不存在返回错误提示
            return Result.error("用户不存在");
        }else{
            //用户存在获取密码进行校验,使用JWT进行校验
            System.out.println(user.getPassword());
            if (user.getPassword().equals(Md5Util.getMD5String(password))) {
//                生成jwt
                HashMap<String, Object> jwt = new HashMap<>();
                jwt.put("id",user.getId());
                jwt.put("username",user.getUsername());
                String token = JwtUtil.genToken(jwt);
//                1.登录成功后，给浏览器响应令牌的同时，把该令牌存储到redis中
                stringRedisTemplate.opsForValue().set(token,token);//在redis中将token设置为键和值
                return Result.success(token);
            }else {
                return Result.error("密码验证失败");
            }
        }
    }

//    获取登录后用户信息
    @GetMapping("/userInfo")
    public Result<User> getUserInfo() {
      Map<String,Object> usermap=  ThreadLocalUtil.get();
        String username = (String) usermap.get("username");
        User user = userService.findUserByName(username);
        return Result.success(user);
    }
 //更新用户基本信息
    @PutMapping("/updateUser")
    public Result updateUserInfo(@RequestBody @Validated User user) {
     Result result=   userService.updateUser(user);
     return result;
    }
 //更新用户头像
    @PatchMapping("/updateAvatar")
    public Result updateAvatar(@RequestParam @URL String avatarUrl) {
      return   userService.updateAvatar(avatarUrl);
    }

 //更新密码updatePwd
    @PatchMapping("/updatePwd")
    public Result updatePwd(@RequestBody Map<String,String> params ,@RequestParam("Authorization")  String token) {
        String oldPassword = params.get("oldPassword");
        String newPassword = params.get("newPassword");
        String rePassword = params.get("rePassword");
        //判断原密码是否正确
        Map<String,Object> map= ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User user = userService.findUserByName(username);
        if(!user.getPassword().equals(Md5Util.getMD5String(oldPassword))) {
            return Result.error("原密码不正确，请重新输入");
        }
        //判断两次输入的密码是否一致
        if (!newPassword.equals(rePassword)) {
            return Result.error("两次输入的密码不正确请重新输入");
        }
        //当用户修改密码成功后，删除redis中存储的旧令牌
         stringRedisTemplate.opsForValue().getOperations().delete(token);
        return  userService.updatePwd(newPassword);

    }
}
